<template>
  <div :style="{ width: '200px' }">
    <a-tag
      v-for="(tag, i) in tags"
      :key="tag"
      color="blue"
      :closable="true"
      @close="() => removeTag(i)"
      class="btn"
    >
      <a
        @click="
          () => {
            clickTag(tag);
          }
        "
      >
        {{ tag }}
      </a>
    </a-tag>
    <a-input
      v-model="inputValue"
      v-if="inputVisible"
      ref="input"
      type="text"
      size="small"
      :style="{ width: '78px' }"
      @blur="handleInputConfirm"
    />
    <a-tag
      v-else
      style="background: #fff; borderstyle: dashed"
      @click="showInput"
      class="btn"
    >
      <a-icon type="plus" /> 标签
    </a-tag>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  props: {
    tags: Array, //子组件使用value接收父组件的传参
    clickTag: Function,
    datatype: {
      type: String,
      default: "string",
    },
  },
  data() {
    return {
      inputVisible: false,
      inputValue: "",
    };
  },
  methods: {
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function () {
        this.$refs.input.focus();
      });
    },
    removeTag(i) {
      const _tags = [...this.tags];
      _tags.splice(i, 1);
      this.$emit("changeTags", _tags);
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue && !_.includes(this.tags, inputValue)) {
        this.$emit("changeTags", [...this.tags, inputValue]);
      }
      Object.assign(this, {
        inputVisible: false,
        inputValue: null,
      });
    },
  },
};
</script>
<style lang="less" scoped>
.btn {
  margin: 2px 4px;
}
</style>
